package com.fang.algorithm.zuo.basis;

/**
 * @author fanglingxiao
 * @version 1.0
 * @description 通过二分法判断一个数是否存在
 * 给定一个有序的数组，判断一个数是否存在
 * @date 2022/7/30 6:19 下午
 **/
public class BinarySearch1 {
    public static void main(String[] args) {
        int[] arr = new int[]{1, 2, 3, 3, 3, 3, 4, 5, 6, 9, 11, 12, 14};
        int num = 5;
        boolean result = checkExist(arr, num);
        System.out.println(result);
    }

    private static boolean checkExist(int[] arr, int num) {
        if (null == arr || arr.length < 2) {
            return null != arr && (arr[0] == num);
        }
        int L = 0, R = arr.length - 1;
        while (L < R) {
            // (L + R)/2 = L + (R-L)/2 = L + ((R - L) >> 1)
            int mid = L + ((R - L) >> 1);
            if (arr[mid] == num) {
                return true;
            } else if (arr[mid] > num) {
                R = mid - 1;
            } else {
                L = mid + 1;
            }
        }
        return arr[L] == num;
    }
}
